﻿import 'dart:async';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'countdown_state.dart';
import '../routes.dart';

/// 运动倒计时控制器
class CountdownLogic extends GetxController {
  final CountdownState state = CountdownState();
  Timer? _countdownTimer;

  @override
  void onInit() {
    super.onInit();

    // 获取传入参数
    final arguments = Get.arguments as Map<String, dynamic>?;
    if (arguments != null) {
      state.exerciseName.value = arguments['exerciseName'] ?? 'GPS散步';
      state.targetInfo.value = arguments['targetInfo'] ?? '3.00千米';
    }

    // 自动开始倒计时
    startCountdown();
  }

  @override
  void onClose() {
    _countdownTimer?.cancel();
    super.onClose();
  }

  /// 开始倒计时
  void startCountdown() {
    state.isCountingDown.value = true;
    state.countdownNumber.value = 3;

    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (state.countdownNumber.value > 1) {
        state.countdownNumber.value--;
      } else {
        // 倒计时结束
        timer.cancel();
        state.isCountingDown.value = false;
        state.isCompleted.value = true;

        // 延迟200ms后跳转到运动记录页面
        Future.delayed(const Duration(milliseconds: 200), () {
          navigateToExerciseRecording();
        });
      }
    });
  }

  /// 立即开始运动
  void startImmediately() {
    _countdownTimer?.cancel();
    state.isCountingDown.value = false;
    navigateToExerciseRecording();
  }

  /// 跳转到运动记录页面
  void navigateToExerciseRecording() {
    // 传递运动信息到记录页面，用户需要手动点击开始
    final arguments = Get.arguments as Map<String, dynamic>?;

    // 检查是否为非GPS运动
    final isNonGpsExercise = arguments?['isNonGpsExercise'] ?? false;

    if (isNonGpsExercise) {
      // 非GPS运动跳转到非GPS运动记录页面
      Get.toNamed(ExerciseRoutes.nonGpsExerciseRecording, arguments: arguments);
    } else {
      // GPS运动跳转到GPS运动记录页面
      Get.toNamed(ExerciseRoutes.exerciseRecording, arguments: arguments);
    }
  }

  /// 返回上一页
  void goBack() {
    _countdownTimer?.cancel();
    Get.back();
  }

  /// 获取倒计时显示文本
  String getCountdownText() {
    if (state.isCompleted.value) {
      return 'GO!';
    } else {
      return state.countdownNumber.value.toString();
    }
  }

  /// 获取提示文本
  String getHintText() {
    if (state.isCompleted.value) {
      return '开始运动！';
    } else if (state.isCountingDown.value) {
      return '准备开始';
    } else {
      return '即将开始';
    }
  }
}
